package com.example.futureai.config.nutz;

import com.example.futureai.config.nutz.core.SpringDaoRunner;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.nutz.dao.DaoInterceptor;
import org.nutz.dao.SqlManager;
import org.nutz.dao.impl.DaoRunner;
import org.nutz.dao.impl.FileSqlManager;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.util.tables.TablesFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @ClassName: NutzDaoAutoConfiguration
 * @Description:
 * @Author: YourName
 * @Date: 2025/1/7
 */

@Configuration
@ConditionalOnClass(Dao.class)
@ConditionalOnBean(TablesFilter.class)
@Slf4j
public class NutzDaoAutoConfiguration {

    @Autowired
    NutzDaoAutoConfigurationProperties nutzDaoAutoConfigurationProperties;

    @Autowired
    TablesFilter tablesFilter;

    @Bean
    @ConditionalOnMissingBean(DaoRunner.class)
    public DaoRunner daoRunner() {
        return new SpringDaoRunner();
    }


    @Bean
    @ConditionalOnMissingBean
    public SqlManager sqlManager() {
        String[] paths = nutzDaoAutoConfigurationProperties.getSqlManager().getPaths();
        if (paths == null) {
            paths = new String[]{"sqls"};
        }
        return new FileSqlManager(paths);
    }
    @Bean
    public Dao dao(DataSource dataSource, SqlManager sqlManager, DaoRunner daoRunner, ApplicationContext context) {
        NutDao dao = new NutDao(dataSource, sqlManager);
        dao.setRunner(daoRunner);
        Map<String, DaoInterceptor> interceptors = context.getBeansOfType(DaoInterceptor.class);
        interceptors.values().forEach(dao::addInterceptor);
        if (this.nutzDaoAutoConfigurationProperties.getInterceptor().isTime()) {
            dao.addInterceptor("time");
        }
        return dao;
    }

    @Bean
    @ConditionalOnMissingBean //注解的主要作用是确保当 Spring 容器中不存在指定类型的 Bean 时，才创建一个新的 Bean。这对于配置覆盖和自定义 Bean 特别有用，因为它允许开发者在需要时提供自己的实现，而不需要修改现有的自动配置。
    public NutzDatabaseInitializer nutzDatabaseInitializer(DataSource dataSource, Dao dao){
        System.out.println("nutz初始化开始====================");
        log.info("nutz初始化开始");
        return new NutzDatabaseInitializer(nutzDaoAutoConfigurationProperties, dao, tablesFilter);
    }
}
